<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use think\Db;

class Exampaper extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'exam_paper';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'mode_text',
        'status_text',
        'limit_time_text',
        'start_time_text',
        'end_time_text'
    ];
    

    
    public function getModeList()
    {
        return [
            // 'RANDOM' => __('Mode RANDOM'), 
            'FIX' => __('Mode FIX')
        ];
    }
    
    public function getStatusList()
    {
        return ['NORMAL' => __('NORMAL'), 'HIDDEN' => __('HIDDEN')];
    }


    public function getModeTextAttr($value, $data)
    {
        $value = $value ?: ($data['mode'] ?? '');
        $list = $this->getModeList();
        return $list[$value] ?? '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getLimitTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['limit_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['start_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['end_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setLimitTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function addFixExamQuestion($data)
    {
        $questions = $data['questions'];
        $exampaper = $data['exampaper'];
        # 把题库数据 写入 考试表
        $insert = [];
        try {
            foreach ($questions as $key => $question) {
                // 检查原题目是否存在
                $questionInfo = Db::name('question')->where('id', $question["id"])->find();
                // 检查题目是否已经在该试卷中存在，避免重复添加
                $existingQuestion = Db::name('exam_paper_question')->where([
                    'paper_id' => $exampaper['id'],
                    'question_id' => $question['id']
                ])->find();
                if (!$existingQuestion) {
                    $insert[] = [
                        'paper_id' => $exampaper['id'],
                        'question_id' => $question['id'],
                        'score' => $question['score'],
                        'answer_config' => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                        'createtime' => time(),
                    ];
                } else {
                    continue;
                }
            }
            if (!empty($insert)) {
                Db::name('exam_paper_question')->insertAll($insert);
            }
        } catch (\Exception $e) {
            \think\Log::error("添加固定题目异常，试卷ID: " . $paper['id'] . ", 错误: " . $e->getMessage());
            throw $e;
        }
    }
}
